<!-- 回款率统计 -->
<template>
  <div class="padding" v-loading="loading">
    <el-card>
      <div slot="header" class="clearfix">
        <span>回款率统计</span>
      </div>
      <el-form
        :inline="true"
        :model="searchCriteria"
        ref="searchCriteria"
        size="mini"
        class=" padding-top-sm flex justify-between"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="数据时间段" prop="statisticDate">
              <el-date-picker
                type="monthrange"
                v-model="searchCriteria.statisticDate"
                value-format="yyyy-MM"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="展示时间段" prop="queryDate">
              <el-date-picker
                type="monthrange"
                v-model="searchCriteria.queryDate"
                value-format="yyyy-MM"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="查询方式" prop="inStockOrAccountDate">
              <el-select v-model="searchCriteria.inStockOrAccountDate">
                <el-option label="入库时间" value="0"></el-option>
                <el-option label="费用时间" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="部门" prop="saleGroupId">
              <el-select v-model="searchCriteria.saleGroupId" filterable clearable placeholder="默认选择全部">
                <el-option v-for="(item, value) in userDeparSource" :key="value" :label="item" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="应收/应付" prop="receiveOrPay">
              <el-select v-model="searchCriteria.receiveOrPay">
                <el-option label="应收" value="0"></el-option>
                <el-option label="应付" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="销售" prop="salesmanIds">
              <el-select
                v-model="searchCriteria.salesmanIds"
                multiple
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="(v, i) in userSource"
                  :key="i"
                  :label="v"
                  :value="i"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="海外仓" prop="orderType">
              <el-select v-model="searchCriteria.orderType" clearable>
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="2021年部门" prop="oldSaleGroupId">
              <el-select v-model="searchCriteria.oldSaleGroupId" filterable clearable placeholder="默认选择全部">
                <el-option v-for="(item, value) in userDeparBackSource" :key="value" :label="item" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-button type="primary" size="mini" @click="statistics"
          >统计</el-button
        >
        <el-button type="warning" size="mini" @click="exportTable" v-if="isShow"
          >导出</el-button
        >
      </el-form>
    </el-card>
    <el-card class="margin-top" v-if="isShow">
      <el-table
        border
        :data="tableData"
        id="out-eltable"
        style="width:100%"
        class="text-sm"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
      >
        <el-table-column
          :fit-header="true"
          :auto-fit="true"
          v-for="(item, index) in tableHead"
          :key="index"
          :label="item.label"
          :prop="item.prop"
        >
          <template slot-scope="scope">
            <div>{{ scope.row[item.prop] }}</div>
            <div v-if="item.prop === 'month'">回款率</div>
            <template v-for="(v, i) in scope.row.returnMoneyDateMap">
              <div v-if="i === item.prop" :key="v.length">
                {{ v.offMoney }}<br />{{ v.returnRate }}
              </div>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
<script>
import { ajax } from "@/store/yg/common/utils";
import { m } from "@/store/yg/common/local";
import { parseTime } from "@/utils";
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default {
  data() {
    return {
      searchCriteria: {
        queryDate: "",
        statisticDate: "",
        inStockOrAccountDate: "0",
        salesmanIds: "",
        saleGroupId: "",
        receiveOrPay: "0",
        orderType: null,
        oldSaleGroupId: null
      },
      isShow: false,
      text: "",
      loading: false,
      saleGroupMap: {},
      saleMap: {},
      userSource: {},
      userDeparSource: {},
      userDeparBackSource: {},
      tableHead: [],
      tableData: []
    };
  },
  mounted() {
    this.userSource = this.$store.state.blank.entry.sources["userSource"];
    this.userDeparSource = this.$store.state.blank.entry.sources[
      "userDeparSource"
    ];
    this.userDeparBackSource = this.$store.state.blank.entry.sources["userDeparBackSource"];
  },
  methods: {
    m(val) {
      return m(val);
    },
    statistics() {
      if (
        !this.searchCriteria.queryDate ||
        !this.searchCriteria.statisticDate
      ) {
        this.$message.error("查询时间段,统计时间段不能为空!");
        return;
      }
      this.statisticReturnRate();
      // let startDate = new Date(this.searchCriteria.queryDate[0]);
      // let startYear = startDate.getFullYear();
      // let startMonth = startDate.getMonth() + 1;

      // let endDate = new Date(this.searchCriteria.queryDate[1]);
      // let endYear = endDate.getFullYear();
      // let endMonth = endDate.getMonth() + 1;

      // if (endMonth - startMonth < 3 && endYear - startYear === 0) {
      //   this.statisticReturnRate();
      // } else if (
      //   (startMonth === 11 || startMonth === 12) &&
      //   startMonth - endMonth === 10
      // ) {
      //   this.statisticReturnRate();
      // } else {
      //   this.$message.error("只能查询三个月内的数据");
      // }
    },
    async statisticReturnRate() {
      let queryStartDate = this.searchCriteria.queryDate[0];
      let queryEndDate = this.searchCriteria.queryDate[1];
      let statisticStartDate = this.searchCriteria.statisticDate[0];
      let statisticEndDate = this.searchCriteria.statisticDate[1];
      this.loading = true;
      let attrs = {};
      attrs["headers"] = {
        "YG-UNIQUE-KEY": "query_return_statistic" + new Date().getTime()
      };
      let res = await ajax(
        "statisticReturnRate",
        {
          queryStartDate: queryStartDate,
          queryEndDate: queryEndDate,
          statisticStartDate: statisticStartDate,
          statisticEndDate: statisticEndDate,
          inStockOrAccountDate: this.searchCriteria.inStockOrAccountDate,
          saleGroupId: this.searchCriteria.saleGroupId,
          receiveOrPay: this.searchCriteria.receiveOrPay,
          orderType: this.searchCriteria.orderType,
          salesmanIds: this.searchCriteria.salesmanIds,
          oldSaleGroupId: this.searchCriteria.oldSaleGroupId
        },
        attrs
      );
      console.log(res);
      if (res.code === 200 && res.data.returnRateCounts.length !== 0) {
        this.text = this.searchCriteria.receiveOrPay == 0 ? "应收" : "应付";
        let anotherTableHead = [
          {
            label: "发出时间",
            prop: "month"
          },
          {
            label: `含税${this.text}金额`,
            prop: "receiveMoney"
          }
        ];

        let col = [];
        for (let i of res.data.x) {
          col.push({
            prop: i,
            label: i
          });
        }
        this.tableHead = [...anotherTableHead, ...col];
        this.tableData = res.data.returnRateCounts;
        this.isShow = true;
        // this.tableData = res.data.returnRateCounts;
      } else if (res.code === 200 && res.data.returnRateCounts.length === 0) {
        this.$message.warning("暂无数据");
      } else if (res.code === 500) {
        this.$message.warning(m(res.message));
      } else {
        this.$message.error(m(res.message));
      }
      this.loading = false;
    },
    // 导出
    exportTable() {
      /* 从表生成工作簿对象 */
      var wb = XLSX.utils.table_to_book(document.querySelector("#out-eltable"));

      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      console.log(`wb`, wb.Sheets.Sheet1);
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          `回款率统计表${parseTime(new Date(), "{y}{m}{d}")}.xlsx`
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    }
  }
};
</script>
